// src/services/scholarsDashboardService/scholarBatchUpdate.ts

import { BASE_URL } from '@/services/apiConfig';

interface ITEDashboardManualUpdate {
  ite_id: number;
  indigenous_student?: string;
  placement_performance?: string;
  grade_updated?: string;
  grade_updated_date?: Date;  // Changed from string to Date
  unsw_attendee_presentation?: string;
  mpc_submitted_date?: Date;  // Changed from string to Date
  mpc_submitted_on_time?: string;
  mpc_call_date?: Date;       // Changed from string to Date
  mpc_call_on_time?: string;
  it_change_approved?: string;
}

interface BatchUpdateResponse {
  message: string;
  count: number;
}

const batchUpdateScholars = async (updates: ITEDashboardManualUpdate[]): Promise<BatchUpdateResponse> => {
  const token = localStorage.getItem('token');
  if (!token) throw new Error('No token found');

  // Convert Date objects to ISO string format for JSON serialization
  const serializedUpdates = updates.map(update => ({
    ...update,
    grade_updated_date: update.grade_updated_date?.toISOString().split('T')[0],
    mpc_submitted_date: update.mpc_submitted_date?.toISOString().split('T')[0],
    mpc_call_date: update.mpc_call_date?.toISOString().split('T')[0],
  }));

  const res = await fetch(`${BASE_URL}/scholars/batch-update`, {
    method: 'PUT',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(serializedUpdates),
  });

  if (!res.ok) {
    let errMsg;
    try {
      errMsg = await res.json();
    } catch {
      errMsg = await res.text();
    }
    throw new Error(`Batch update failed: ${res.status} - ${JSON.stringify(errMsg)}`);
  }

  const data: BatchUpdateResponse = await res.json();
  return data;
};

export { batchUpdateScholars }; 